package kz.kstu.aecdemo.app.util.locator;
import kz.kstu.aecdemo.business.common.exception.ServerNotFoundException;
import org.apache.log4j.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.net.URL;
import java.util.Properties;

/**
 * @author Filipp_Stankevich
 *         created: 8/5/11 2:46 PM
 */
public class EJBLocalServiceLocator extends AbstractServiceLocator{

    private final static String CONTEXT_FACTORY = "org.apache.openejb.client.LocalInitialContextFactory";
    private final static String PROVIDER_URL = "ejbd://localhost:4201";
    private static final String OPENEJB_PROPERTY_CONFIGURATION = "openejb.configuration";
    private static final String OPENEJB_PROPERTY_JNDI = "openejb.jndiname.format";
    private static final String OPENEJB_JNDI_FORMAT = "{deploymentId}";

    private final static Logger LOGGER = Logger.getLogger(EJBLocalServiceLocator.class);

    private InitialContext initialContext;

    public EJBLocalServiceLocator() {}

    @Override
    protected String getServiceFullName(String serviceName) {
        return serviceName;
    }

    @Override
    protected InitialContext getInitialContext() {
        if (initialContext == null) {
            Properties properties = new Properties();
            properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, CONTEXT_FACTORY);
            properties.setProperty(Context.PROVIDER_URL, PROVIDER_URL);
            properties.setProperty(OPENEJB_PROPERTY_CONFIGURATION, getOpenEJBConfig());
            properties.put(OPENEJB_PROPERTY_JNDI, OPENEJB_JNDI_FORMAT);
            // System.setProperty("openejb.logger.external", "true");
            try {
                initialContext = new InitialContext(properties);
            } catch (NamingException e) {
                throw new ServerNotFoundException(e.getMessage(), e);
            }
        }
        return initialContext;
    }

    /**
     * Getting path to the openejb.xml file.
     *
     * @return Path to the config file.
     */
    private String getOpenEJBConfig() {
        URL configURL = this.getClass().getClassLoader().getResource("openejb.xml");
        LOGGER.debug("URL to the openejb.xml : "+ configURL.toExternalForm());
        return configURL.toExternalForm();
    }
}
